//
//  UploadSetViewController.m
//  UEAssistant
//
//  Created by mac on 2017/7/18.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "UploadSetViewController.h"
#import "LoopProgressView.h"
#import "SetTableViewCell.h"
#import "ZZCircleProgress.h"
#import "FileModel.h"
#import "FileStreamOperation.h"
#import "LoginViewController.h"
#import "MJ_DocmentsModel.h"
#import "NSData+UTF8.h"
@interface UploadSetViewController ()<UITableViewDelegate,UITableViewDataSource,NSStreamDelegate>{

    NSMutableArray          *_dataSource;
}

@property (nonatomic, strong) UILabel                                       *titleL;
@property (nonatomic, strong) UITableView                                   *tableView;
@property (nonatomic, strong) LoopProgressView                              *progressView;
@property (nonatomic, strong) UIImageView                                   *docmentView;
@property (nonatomic, strong) UILabel                                       *docmentName;
@property (nonatomic, strong) UILabel                                       *uploadSpeed;
@property (nonatomic, copy)   NSString                                      *docmentRemark;
@property (nonatomic, strong) UIButton                                      *sureButton;
@property (nonatomic, copy)   NSString                                      *doc_name;
@property (nonatomic, copy)   NSString                                      *UUID;
@property (nonatomic, strong) ZZCircleProgress                              *circleTrans;
@property (nonatomic, strong) UILabel                                       *progressLabel;
@property (nonatomic, assign) float                                         fileSize;
@property (nonatomic, strong) UILabel                                       *headerLabel;
@property (nonatomic, strong) NSString                                      *chunk_flag;
@property (nonatomic, assign) BOOL                                          success_pre;

//文件导入参数
@property (nonatomic, copy) NSString                    *docId;
@property (nonatomic, copy) NSString                    *fileName;
@property (nonatomic, strong) NSTimer                   *timer;
@property (nonatomic, strong) FileStreamOperation       *files;//文件流
@property (nonatomic, strong) NSMutableDictionary              *uploadParam;
@property (nonatomic, assign) NSInteger                       count;

@property (assign, nonatomic)MJDocmentsType currentDocmentType;


@property (nonatomic, strong, readwrite) NSOutputStream *   networkStream;
@property (nonatomic, strong, readwrite) NSInputStream *    fileStream;
@end

@implementation UploadSetViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [_titleL setHidden:NO];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [_titleL setHidden:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initlizeDataSource];
    [self initlizeUserface];
}

- (void)initlizeDataSource{

    //把文件分片
    _files = [[FileStreamOperation alloc]initFileOperationAtPath:[shareData.filepath substringFromIndex:7] forReadOperation:YES];

    _uploadParam = [[NSMutableDictionary alloc] init];
    _count = 0;
    _fileSize = [self fileSizeAtPath:[shareData.filepath substringFromIndex:7]]*1.0/1024/1024;
    
    NSString *documentName = [[shareData.filepath substringFromIndex:7] lastPathComponent];
    _docmentRemark = [self judgeTypeWithName:documentName];
    //获取UUID
    [self getUUID];
    
}

- (void)initlizeUserface{

    self.view.backgroundColor = [UIColor whiteColor];
    _titleL = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 20)];
    _titleL.center = CGPointMake(self.view.center.x, 20);
    _titleL.backgroundColor = [UIColor clearColor];
    _titleL.text = @"上传设置";
    _titleL.textAlignment = NSTextAlignmentCenter;
    _titleL.textColor = [UIColor colorWithHexString:@"#333333"];
    [self.navigationController.navigationBar addSubview:_titleL];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"SetTableViewCell" bundle:nil] forCellReuseIdentifier:SetUplCell];
    [self.view addSubview:self.sureButton];
}

#pragma UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    if (section == 0) {
        return 1;
    }
    else{
        return _dataSource.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 40*Radio;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return 0.001f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (section == 0) {
        
        UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 30*Radio)];
        baseView.backgroundColor = RGB(247, 247, 247, 1);
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15*Radio, 20*Radio, 100, 20*Radio)];
        label.backgroundColor = [UIColor clearColor];
        label.text = @"上传文件";
        label.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
        label.textColor = RGB(161,161,161, 1);
        [baseView addSubview:label];
        return baseView;
    }
    else{
        
        UIView *baseView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, 30*Radio)];
        baseView.backgroundColor = RGB(247, 247, 247, 1);
        [baseView addSubview:self.headerLabel];
        return baseView;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SetUplCell];
    cell.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
    cell.titleLabel.textColor = RGB(75, 75, 75, 1);
    cell.titleLabel.text = _dataSource[indexPath.row];
    cell.switchView.transform= CGAffineTransformMakeScale(0.8,0.8);
    cell.switchView.onTintColor = mainColor;
    
    if (indexPath.section == 0) {
        //移除switch和title
        [cell.switchView removeFromSuperview];
        [cell.titleLabel removeFromSuperview];
        //添加自定义视图
        _progressView =[[LoopProgressView alloc]initWithFrame:CGRectMake(Screen_Width - 60*Radio, 5*Radio, 40*Radio, 40*Radio)];
        [cell addSubview:_progressView];
        [self addCusViewToCell:cell];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

}

#pragma mark -- get UUID
- (void)getUUID{

    [AvailableNetWorking getWithUrl:getUUID_connector params:@{} successHandler:^(id responseObject) {
        NSString *str = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        _UUID = str;
        //先拿UUID再上传文件流
        [self uploadStreamFile];
    } falureHandler:^(NSError *error) {
        
    }];
}
#pragma mark -- 分片上传文件流

- (void)uploadStreamFile{
    
    _UUID = [_UUID stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    _UUID = [_UUID stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    _uploadParam[@"projectId"] = self.projectId;
    _uploadParam[@"size"] = [NSString stringWithFormat:@"%zd",_files.fileSize];
    _uploadParam[@"chunks"] = [NSString stringWithFormat:@"%zd",_files.fileFragments.count];
    _uploadParam[@"identifier"] = _UUID;
    
    NSString *documentName = [[shareData.filepath substringFromIndex:7] lastPathComponent];
    FileFragment *fragment = _files.fileFragments[_count];
    NSData *data = [_files readDateOfFragment:fragment];
    _uploadParam[@"chunkSize"] = [NSString stringWithFormat:@"%zd",fragment.fragmentSize];
    _uploadParam[@"chunk"] = [NSString stringWithFormat:@"%zd",_count];
    _uploadParam[@"name"] = documentName;
    [LSProgressHUD showWithMessage:@"正在上传文件，请勿关闭App..."];
    [AvailableNetWorking uploadDataWithParameter:_uploadParam
                                     data:data
                                 progress:^(CGFloat progress) {
                                     
                                     dispatch_async(dispatch_get_main_queue(), ^{
                                         _progressView.progressValue = progress;
                                         _progressLabel.text = [NSString stringWithFormat:@"%.f%%",progress*100];
                                         if (_count > 0) {
                                             _uploadSpeed.text = [NSString stringWithFormat:@"%.2fM/%.2fM",fragment.fragmentSize/1024.0/1024.0*progress+_count*5.0,_fileSize];
                                         }else{
                                            _uploadSpeed.text = [NSString stringWithFormat:@"%.2fM/%.2fM",fragment.fragmentSize/1024.0/1024.0*progress,_fileSize];
                                         }
                                     });
                                 } successHander:^(id responseObject) {
                                     //200为正确上传，其他为返回的错误问题
                                     if ([responseObject[@"code"] integerValue] > 199 && [responseObject[@"code"] integerValue] < 299) {
                                         _docId = [NSString stringWithFormat:@"%@",responseObject[@"flag"]];
                                         _uploadParam[@"flag"] = _docId;
                                         if (_files.fileFragments.count - 1 > _count) {
                                             _count += 1;
                                             [LSProgressHUD hideForWindow];
                                             [self uploadStreamFile];
                                         }
                                     }else{
                                         [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:YES];
                                         [LSProgressHUD hideForWindow];
                                         return;
                                     }
                
                                     TGLog(@"responseObject = %@",responseObject);
                                     [LSProgressHUD hideForWindow];
                                 } failureHander:^(NSError *error) {
                                     [LSProgressHUD hideForWindow];
                                 }];

}

//文件导入设置
- (void)SureButtonCliced{
    
    MJ_DocmentsModel *docmentsModel = [[MJ_DocmentsModel alloc] init];
    NSArray *cellIndexPathArray = self.tableView.indexPathsForVisibleRows;
    NSMutableArray *resultArray = [[NSMutableArray alloc] init];
    //获取到当前选择的开关设置
    for (NSIndexPath *indexPath in cellIndexPathArray) {
        if (indexPath.section == 1) {
            SetTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            NSString * one = [NSString stringWithFormat:@"%zd",(cell.switchView.on ? 1 : 0)];
            [resultArray addObject:one];
        }
    }
    //设置参数字典
    BOOL result = [docmentsModel docmentWithType:_currentDocmentType result:resultArray];
    if (!result) {
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"不支持的文件类型~" andTitleColor:[UIColor whiteColor] andCancel:YES];
        return;
    }
    NSDictionary *docmentsSettingDic = [docmentsModel dictionaryWithProperty];
    TGLog(@"文件设置字典----%@",docmentsSettingDic);
    NSString *jsonSetting = [self dictionaryToJson:docmentsSettingDic];
    
    NSDictionary *dic = @{@"projectId":self.projectId,
                          @"inconfig":jsonSetting,
                          @"docIds":_docId,
                          @"filePath":[NSString stringWithFormat:@"%@/%@/",self.projectId,_docId],
                          @"docName":[[shareData.filepath substringFromIndex:7] lastPathComponent],
                          @"sourcelangkey":self.sourcelangkey,
                          @"vmId":_owner_id};
    
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:FileSet_connector] params:dic successHandler:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) {
            NSLog(@"文件导入 == %@",responseObject[@"message"]);
            //查询解析结果
//            UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//                while (TRUE) {
//                    if (!_success_pre) {
//                        // 每隔1秒执行一次（当前线程阻塞1秒）
//                        [NSThread sleepForTimeInterval:1];
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [[UIApplication sharedApplication] cancelAllLocalNotifications];
//                        });
                        //每隔1秒执行一次该方法
                        [self checkFileResultStu];
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
//                        });
//                    }else{
//                        [self.navigationController popToRootViewControllerAnimated:YES];
//                    }
//                };
//            });
        }else{
            TGLog(@"返回错误-------------%@",responseObject[@"message"]);
        }
    } falureHandler:^(NSError *error) {
        TGLog(@"返回错误-------------%@",error);
    }];
}

- (void)checkFileResultStu{

    NSDictionary *dic = @{@"docIds":_docId,
                          @"projectId":self.projectId};
    [LSProgressHUD hideForWindow];
    [LSProgressHUD showWithMessage:@"文件正在解析中..."];
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:checkFileResult_connector] params:dic successHandler:^(id responseObject) {
        TGLog(@"文件状态=%@",responseObject);
        NSDictionary *dic = responseObject[@"result"][_docId];
        if ([dic[@"doc_status"] integerValue] != 0) {
            [self checkFileResultStu];
        }else{
            [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"上传文件成功！" andTitleColor:[UIColor whiteColor] andCancel:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [LSProgressHUD hideForWindow];
                [self.navigationController popToRootViewControllerAnimated:YES];
            });
        }
        [LSProgressHUD hideForWindow];
    } falureHandler:^(NSError *error) {
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"网络短路啦~" andTitleColor:[UIColor whiteColor] andCancel:YES];
        [LSProgressHUD hideForWindow];
    }];
}


#pragma mark -- 获取文件大小
-(long long) fileSizeAtPath:(NSString*)filePath{
    
    NSFileManager* manager =[NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

#pragma mark -- 判断后缀
- (NSString *)judgeTypeWithName:(NSString *)string{

    NSArray *array = [string componentsSeparatedByString:@"."];
    
    if ([array.lastObject isEqualToString:@"doc"] || [array.lastObject isEqualToString:@"docx"] || [array.lastObject isEqualToString:@"rtf"]) {
        
        _dataSource = [NSMutableArray arrayWithObjects:@"导入隐藏内容",@"导入批注",nil];
        self.headerLabel.text = @"Microsoft Word";
        _currentDocmentType = MJDocmentsTypeWord;
        
        return @"word";
    }
    else if ([array.lastObject isEqualToString:@"xls"] || [array.lastObject isEqualToString:@"xlsx"]){
        
        _dataSource = [NSMutableArray arrayWithObjects:@"导入隐藏内容",@"导入表名",@"导入批注",nil];
        self.headerLabel.text = @"Microsoft Excel";
        _currentDocmentType = MJDocmentsTypeExcel;
        
        return @"Exel";
    }
    else if ([array.lastObject isEqualToString:@"ppt"] || [array.lastObject isEqualToString:@"pptx"]){
        
        _dataSource = [NSMutableArray arrayWithObjects:@"导入隐藏内容",@"导入备注",@"导入节标题",nil];
        self.headerLabel.text = @"Microsoft PowerPoint";
        _currentDocmentType = MJDocmentsTypePPT;
        
        return @"ppt";
    }
    else if ([array.lastObject isEqualToString:@"dwg"] || [array.lastObject isEqualToString:@"dxf"]){
        
        _dataSource = [NSMutableArray arrayWithObjects:@"导入非译句子",@"导入关闭文字",@"导入冻结文字",@"导入锁定文字",nil];
        self.headerLabel.text = @"CAD图纸";
        _currentDocmentType = MJDocmentsTypeCAD;
        
        return @"CAD";
    }
    else if ([array.lastObject isEqualToString:@"vsdx"]){
        
        _dataSource = [NSMutableArray arrayWithObjects:@"导入批注",@"导入页名",nil];
        self.headerLabel.text = @"Microsoft Visio";
        _currentDocmentType = MJDocmentsTypVisio;
        
        return @"visio";
    }
    else if ([array.lastObject isEqualToString:@"sdlxliff"]){
        
        _dataSource = [NSMutableArray array];
        _currentDocmentType = MJDocmentsTypeSdlxliff;
        return @"sdlxliff";
    }
    else if ([array.lastObject isEqualToString:@"xmind"]){
        _dataSource = [NSMutableArray arrayWithObjects:@"导入画布名",@"导入批注",@"导入备注",@"导入标签",nil];
        self.headerLabel.text = @"思维导图";
        _currentDocmentType = MJDocmentsTypeXmind;
        return @"xmind";
    }
    else{

        return @"pdf";
    }
}

- (void)addCusViewToCell:(UIView *)cell{

    _progressLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 40*Radio, 20*Radio)];
    _progressLabel.center = _progressView.center;
    _progressLabel.textAlignment = NSTextAlignmentCenter;
    _progressLabel.text = @"0%";
    _progressLabel.textColor = mainColor;
    _progressLabel.font = [UIFont systemFontOfSize:FLEXIBLE(12)];
    [cell addSubview:_progressLabel];
    
    _docmentView = [[UIImageView alloc]initWithFrame:CGRectMake(15*Radio, 10*Radio, 30*Radio, 30*Radio)];
    _docmentView.image = [UIImage imageNamed:_docmentRemark];
    [cell addSubview:_docmentView];
    
    _docmentName = [[UILabel alloc]initWithFrame:CGRectMake(_docmentView.frame.origin.x+_docmentView.frame.size.width+10*Radio, _docmentView.frame.origin.y-2*Radio, 250*Radio, 18*Radio)];
    _docmentName.backgroundColor = [UIColor clearColor];
    _docmentName.textColor = RGB(75, 75, 75, 1);
    _docmentName.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
    _docmentName.text = [[shareData.filepath substringFromIndex:7] lastPathComponent];
    [cell addSubview:_docmentName];
    
    _uploadSpeed = [[UILabel alloc]initWithFrame:CGRectMake(_docmentView.frame.origin.x+_docmentView.frame.size.width+10*Radio, _docmentView.frame.origin.y+18*Radio, 150*Radio, 10*Radio)];
    _uploadSpeed.backgroundColor = [UIColor clearColor];
    _uploadSpeed.textColor = RGB(210, 210, 210, 1);
    _uploadSpeed.font = [UIFont systemFontOfSize:FLEXIBLE(12)];
    _uploadSpeed.text = @"正在连接...";
    [cell addSubview:_uploadSpeed];

}

#pragma mark -- 转json
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:0 error:&parseError];
    NSString *jsonString;
    if (!jsonData) {
        
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\" withString:@""];
    jsonString = [jsonString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return jsonString;
    
}


#pragma mark -- getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = RGB(250, 250, 250, 1);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = RGB(241, 241, 241, 1);
        _tableView.rowHeight = 50*Radio;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

- (UIButton *)sureButton{
    
    if (!_sureButton) {
        
        _sureButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _sureButton.frame = CGRectMake(0, Screen_Height - 50*Radio-64, Screen_Width, 50*Radio);
        _sureButton.backgroundColor = RGB(57, 186, 241, 1);
        [_sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_sureButton setTitle:@"确定" forState:UIControlStateNormal];
        [_sureButton addTarget:self action:@selector(SureButtonCliced) forControlEvents:UIControlEventTouchUpInside];
        _sureButton.titleLabel.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
    }
    return _sureButton;
}
- (UILabel *)headerLabel{

    if (!_headerLabel) {
        
        _headerLabel = [[UILabel alloc]initWithFrame:CGRectMake(15*Radio, 20*Radio, 150, 20*Radio)];
        _headerLabel.backgroundColor = [UIColor clearColor];
        _headerLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
        _headerLabel.textColor = RGB(161,161,161, 1);
        _headerLabel.text = @"不支持此格式";
    }
    return _headerLabel;
}

@end
